import { computed, ref, unref } from 'vue';
import { cloneDeep, isUndefined } from 'lodash-es';
import { getDataPeer, getKesArr } from './utls';
import type {
  SzTreePropsType,
  TreeDataArr,
  TreeMethods,
  UseSzTreeMethods,
} from '../types/treeType';
import type { Nullable } from '#/types/global';
import type { TreeKey } from 'element-plus/es/components/tree-v2/src/types';

export type RegisterFn = (formInstance: TreeMethods) => void;
type UseSzTree = [RegisterFn, UseSzTreeMethods];
type Props = Partial<SzTreePropsType>;

export function useTree(treeProps?: Props): UseSzTree {
  const selectObj = ref<TreeDataArr>();
  const selectParentArr = ref<TreeDataArr[]>();
  const expandedKeys = ref<string[]>([]);
  const gData = ref<any>();
  const modal = ref<Nullable<any>>(null);
  const isLoading = ref<boolean>(false);
  //事件
  const setPropEvent = {
    // 选中
    onCurrentChange: (data: TreeDataArr) => {
      // console.log('选中tree', data);
      if (selectObj.value?.key == data.key) {
        getInstance()?.setTreeProps({
          currentKey: null,
        });
        selectObj.value = undefined;
        selectParentArr.value = undefined;
      } else {
        selectObj.value = data;
        selectParentArr.value = cloneDeep(
          unref(getDataPeer(gData, selectObj.value?.key as string)),
        );
      }
    },
    onNodeClick: (data: TreeDataArr) => {
      // console.log('点击', data);
      // 设置后才能取消选中
      getInstance()?.setTreeProps({
        currentKey: null,
      });
    },
    // 节点被展开时触发的事件
    onNodeExpand: (data: TreeDataArr) => {
      // console.log('展开时', data.key);
      expandedKeys.value?.push(data.key);
    },
    // 节点被收起时触发的事件
    onNodeCollapse: (data: TreeDataArr) => {
      // console.log('收起时', data.key);
      const index = unref(expandedKeys).indexOf(data.key);
      if (index > -1) {
        expandedKeys.value.splice(index, 1);
      }
    },
  };

  const register = (modalInstance: TreeMethods) => {
    modal.value = modalInstance;
    const propsd = { ...setPropEvent, ...treeProps };
    modalInstance?.setTreeProps(propsd);
  };

  const getInstance = () => {
    const instance = unref(modal);
    if (!instance) {
      console.error('SzTree 没有实例');
    }
    return instance;
  };
  const expandStateComp = computed(() => {
    //   code 1展开  2收起   3不可用
    let code = 3;
    if (isUndefined(selectObj.value)) {
      if (
        expandedKeys.value.length == 0 ||
        !(expandedKeys.value as string[]).includes(gData.value[0].key as string)
      ) {
        code = 1;
      } else {
        code = 2;
      }
    } else {
      if (selectObj.value.children && selectObj.value.children.length) {
        const fild = expandedKeys.value.some((value) => {
          return value == selectObj.value?.key;
        });
        if (fild) {
          code = 2;
        } else {
          code = 1;
        }
      } else {
        code = 3;
      }
    }
    return code;
  });

  const methods: UseSzTreeMethods = {
    setTreeProps: (props: Partial<SzTreePropsType>): void => {
      if (props.treeData) {
        gData.value = props.treeData;
      }
      if (Reflect.has(props, 'expandedKeys')) {
        expandedKeys.value = props.expandedKeys!;
      }
      getInstance()?.setTreeProps(props);
    },
    /**
     * 展开状态
     */
    expandStateComp,
    /**
     *  展开收起事件
     */
    expandTap() {
      if (isUndefined(selectObj.value)) {
        if (unref(expandStateComp) == 1) {
          // 展开
          expandedKeys.value = getKesArr(gData.value);
        } else {
          expandedKeys.value = [];
        }
        getInstance()?.setTreeProps({
          expandedKeys: unref(expandedKeys),
        });
      } else {
        const selectKey = selectObj.value?.key;
        if (unref(expandStateComp) == 1) {
          //展开
          const keysArr: string[] = getKesArr(gData.value);
          const pushArr: string[] = [];
          keysArr.forEach((e: string) => {
            if (e.includes(selectKey)) {
              pushArr.push(e);
            }
          });
          expandedKeys.value = [...unref(expandedKeys), ...unref(pushArr)];
          getInstance()?.setTreeProps({
            expandedKeys: unref(expandedKeys),
          });
        } else if (unref(expandStateComp) == 2) {
          const keysArr = cloneDeep(unref(expandedKeys));
          const dataArr: string[] = [];
          keysArr.forEach((e: string) => {
            if (!e.includes(selectKey)) {
              dataArr.push(e);
            }
          });
          expandedKeys.value = dataArr;
          getInstance()?.setTreeProps({
            expandedKeys: unref(expandedKeys),
          });
        }
      }
    },
    /**
     * 获取selectObj
     */
    getSelectObjComp: computed(() => selectObj.value),
    /**
     * 可移动状态 1上移 2下移  3上下  4不可移动
     */
    getMoveComp: computed(() => {
      // 1上移 2下移  3上下  4不可移动
      let code = 4;
      if (isUndefined(selectParentArr.value)) {
        code = 4;
      } else {
        const parent = isUndefined(selectParentArr.value) ? gData.value : selectParentArr.value;
        let index = -1;
        parent.forEach((e: TreeDataArr, indexd: number) => {
          if (e.key == selectObj.value?.key) {
            index = indexd;
          }
        });
        if (index == -1) {
          code = 4;
        } else if (index == 0) {
          if (parent.length == 1) {
            code = 4;
          } else {
            code = 2;
          }
        } else if (index == parent.length - 1) {
          code = 1;
        } else {
          code = 3;
        }
      }
      return code;
    }),
    /**
     * 移动事件
     */
    moveTap(type: 'up' | 'down', api) {
      let index = -1;
      if (!isUndefined(selectObj.value)) {
        const dataOne = getDataPeer(gData, selectObj.value?.key as string);
        dataOne.value.forEach((e: TreeDataArr, indexd: number) => {
          if (e.key == selectObj.value?.key) {
            index = indexd;
          }
        });
        const dataTwo: any = dataOne.value[index];
        const dataThree: any = type == 'up' ? dataOne.value[index - 1] : dataOne.value[index + 1];
        const params = [
          {
            id: dataTwo.id,
            sn: dataThree.sn,
          },
          {
            id: dataThree.id,
            sn: dataTwo.sn,
          },
        ];
        api(params).then(() => {
          if (type == 'up') {
            dataOne.value.splice(index - 1, 0, dataTwo as TreeDataArr);
            dataOne.value.splice(index + 1, 1);
          } else {
            dataOne.value.splice(index, 1);
            dataOne.value.splice(index + 1, 0, dataTwo as TreeDataArr);
          }
          // 修改数据
          dataOne.value.map((e: any) => {
            const oneData: any = params.filter((fil) => fil.id == e.id);
            if (oneData.length) {
              e.sn = oneData[0].sn;
            }
            return e;
          });
          //   console.log('移动后', dataOne)
          selectParentArr.value = cloneDeep(dataOne.value);
          getInstance()?.setTreeProps({
            treeData: gData.value,
          });
        });
      }
    },
    setSelectObj(e: TreeDataArr | undefined) {
      selectObj.value = e;
      if (isUndefined(e)) {
        getInstance()?.setTreeProps({
          currentKey: '',
        });
      } else {
        getInstance()?.setTreeProps({
          currentKey: e.key,
        });
      }
    },
    treesCrollTo: () => {
      getInstance()?.treesCrollTo();
    },
    setLoading(bool: boolean) {
      isLoading.value = bool;
      getInstance()?.setLoading(bool);
    },
    getLoading: computed(() => isLoading.value),
    getTreeRef: computed(() => {
      return getInstance()?.getTreeRef;
    }),
    setCheckedKeys: (keys: TreeKey[]) => {
      getInstance()?.setCheckedKeys(keys);
    },
    /**若节点可被选择（即show-checkbox为 true），则返回目前被选中的节点所组成的数组 */
    getCheckedNodes: (bool?: boolean) => {
      const getBool = isUndefined(bool) ? false : bool;
      return getInstance()?.getCheckedNodes(getBool);
    },
  };
  return [register, methods];
}
